package de.clapp.backend.requests;

import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.google.gson.reflect.TypeToken;

import de.clapp.backend.database.Conn;
import de.clapp.backend.database.Queries;
import de.clapp.data.Artikel;

public class MenucardRequest implements ServerRequest
{

    private static final long serialVersionUID = 1400055129997403753L;

    private ArrayList<Artikel> menucard;

    @Override
    public Type getReturnType()
    {
        return new TypeToken<ArrayList<Artikel>>()
        {
        }.getType();
    }

    @Override
    public Object getItem()
    {
        return this.menucard;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void setItem(Object item)
    {
        this.menucard = (ArrayList<Artikel>) item;

    }

    @Override
    public Object execute()
    {
        menucard = new ArrayList<Artikel>();
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try
        {
            con = Conn.getInstance().clientCon;
            pstmt = con.prepareStatement(Queries.GET_ARTIKEL);
            rs = pstmt.executeQuery();
            while (rs.next())
            {
                // ID_ARTIKEL, NAME, EINZELPREIS, KATEGORIE
                Artikel artikel = new Artikel();
                artikel.setIdArtikel(rs.getInt("ID_ARTIKEL"));
                artikel.setName(rs.getString("NAME"));
                artikel.setEinzelPreis(rs.getDouble("EINZELPREIS"));
                artikel.setKategorie(rs.getString("KATEGORIE"));

                menucard.add(artikel);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (pstmt != null)
            {
                try
                {
                    pstmt.close();
                }
                catch (SQLException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (rs != null)
            {
                try
                {
                    rs.close();
                }
                catch (SQLException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return menucard;
    }
}
